package day11;

public class SqQueue<T> implements IQueue<T> {
    private T[] queueElem;
    private int front;
    private int rear;
    private int maxSize;

    public SqQueue(int maxSize) {
        front = rear = 0;
        queueElem = (T[]) new Object[maxSize];
        this.maxSize = maxSize;
    }

    @Override
    public void clear() {
        front = rear = 0;
    }

    @Override
    public boolean isEmpty() {
        return rear == front;
    }

    @Override
    public int length() {
        return rear - front;
    }

    @Override
    public T peek() {
        if (isEmpty()){
            return null;
        }
        return queueElem[front];
    }

    @Override
    public void offer(T x) throws Exception {
        if (rear == maxSize){
            throw new Exception("队列已满");
        }
        queueElem[rear] = x;
        rear++;
    }

    @Override
    public T poll() {
        if (rear == front)
            return null;
        T p = queueElem[front];
        front ++;
        return p;
    }

    @Override
    public void display() {
        if (!isEmpty()){
            for (int i = front;i < rear;i++){
                System.out.println(queueElem[i] + " ");
            }
        }else {
            System.out.println("此队列已空");
        }
    }
}
